import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || '{}'))
  const isLoggedIn = computed(() => !!token.value)

  // 登录
  const login = (loginData) => {
    return new Promise((resolve, reject) => {
      // 模拟登录API调用
      setTimeout(() => {
        if (loginData.username === 'admin' && loginData.password === '123456') {
          const mockToken = 'mock_token_' + Date.now()
          const mockUserInfo = {
            id: 1,
            username: loginData.username,
            nickname: '测试用户',
            avatar: 'https://picsum.photos/80/80?random=1',
            phone: '138****8888'
          }
          
          token.value = mockToken
          userInfo.value = mockUserInfo
          
          localStorage.setItem('token', mockToken)
          localStorage.setItem('userInfo', JSON.stringify(mockUserInfo))
          
          resolve({ success: true, message: '登录成功' })
        } else {
          reject({ success: false, message: '用户名或密码错误' })
        }
      }, 1000)
    })
  }

  // 注册
  const register = (registerData) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({ success: true, message: '注册成功' })
      }, 1000)
    })
  }

  // 登出
  const logout = () => {
    token.value = ''
    userInfo.value = {}
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  // 更新用户信息
  const updateUserInfo = (newInfo) => {
    userInfo.value = { ...userInfo.value, ...newInfo }
    localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    register,
    logout,
    updateUserInfo
  }
})
